<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <label>cookieName:</label> <input type="text" id="cookieName" /><br />
    <label>cookieValue:</label> <input type="text" id="cookieValue" /><br />
    <label>max-age:</label> <input type="text" id="maxAge" /><br />
    <button onclick="setCookie()">设置cookie</button>
    <script>
      var cookieUtil = {
        get: function(name) {
          var cookieName = encodeURIComponent(name) + "=",
            cookieStart = document.cookie.indexOf(cookieName),
            cookieValue = "";

          if (cookieStart > -1) {
            var cookieEnd = document.cookie.indexOf(";", cookieStart);
            if (cookieEnd === -1) {
              cookieEnd = document.cookie.length;
            }
            cookieValue = decodeURIComponent(
              document.cookie.substring(
                cookieStart + cookieName.length,
                cookieEnd
              )
            );
          }
          return cookieValue;
        },

        set: function(name, value, maxAge, path, domain, secure) {
          var cookieText =
            encodeURIComponent(name) + "=" + encodeURIComponent(value);
          if (maxAge) {
            cookieText += "; max-age=" + maxAge;
          }
          if (path) {
            cookieText += "; path=" + path;
          }
          if (domain) {
            cookieText += "; domain=" + domain;
          }
          if (secure) {
            cookieText += "; secure";
          }
          document.cookie = cookieText;
        },

        unset: function(name, path, domain, secure) {
          this.set(name, "", 0, path, domain, secure);
        }
      };

      function setCookie() {
        var name = document.getElementById("cookieName").value;
        var value = document.getElementById("cookieValue").value;
        var maxAge = Number(document.getElementById("maxAge").value);
        cookieUtil.set(name, value, maxAge);
      }
    </script>
  </body>
</html>
